<template>
    <div>
        <el-form :model="spuForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="SPU名称" prop="spuName">
                <el-input v-model="spuForm.spuName"></el-input>
            </el-form-item>
            <el-form-item label="品牌" prop="tmId">
                <el-select v-model="spuForm.tmId" placeholder="请选择活动区域">
                    <el-option :label="tm.tmName" :value="tm.id" v-for="tm in trademarkList" :key="tm.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述" prop="description">
                <el-input type="textarea" rows="4" v-model="spuForm.description"></el-input>
            </el-form-item>
            <el-form-item label="SPU图片" prop="spuImageList">
                <!-- 图片上传提交给后台，后台返回一个图片线上地址 -->
                <el-upload :action="`${baseUrl}/admin/product/upload`" list-type="picture-card"
                    :file-list="spuForm.spuImageList || []"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item label="销售属性" prop="spuSaleAttrList">
                <el-select v-model="spuForm.saleAttr" :placeholder="`还有${unSelectedAttr.length}未选择`">
                    <el-option :label="unSaleAttr.name" :value="`${unSaleAttr.id}:${unSaleAttr.name}`"
                        v-for="unSaleAttr in unSelectedAttr" :key="unSaleAttr.id"></el-option>
                </el-select>
                <el-button type="primary" size="medium" :disabled="!spuForm.saleAttr"
                    @click="addSaleAttr">添加销售属性</el-button>
            </el-form-item>
            <el-form-item>
                <el-table :data="spuForm.spuSaleAttrList" border>
                    <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
                    <el-table-column label="属性名" width="160" prop="saleAttrName"></el-table-column>
                    <el-table-column label="属性值名称列表">
                        <template v-slot="{ row }">
                            <el-tag :key="tag.id" size="mini" v-for="(tag, index) in row.spuSaleAttrValueList" closable
                                :disable-transitions="false" @close="delSaleAttrValueName(row, index)">
                                {{ tag.saleAttrValueName }}
                            </el-tag>
                            <el-button v-if="!row.isEdit" class="button-new-tag" size="mini" icon="el-icon-plus"
                                @click="toInput(row)"></el-button>
                            <el-input class="input-new-tag" v-else v-model="row.newTag" ref="saveTagInput" size="mini"
                                @keyup.enter.native="toButton(row)" @blur="toButton(row)">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="160">
                        <template v-slot="{ row, $index }">
                            <el-button type="danger" size="mini" icon="el-icon-delete"
                                @click="delSaleAttr($index)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save()">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import spuApi from '@/api/spu'
import skuApi from '@/api/sku'
import { Message } from 'element-ui'
import { mapState } from 'vuex'
export default {
    name: 'SpuForm',
    props: ['spuInfo'],
    data() {
        return {
            spuForm: this.spuInfo,
            trademarkList: [],
            baseSaleAttrList: [],
            dialogImageUrl: '',
            dialogVisible: false,
            ruleForm:'',
            rules: {
                spuName: [{ required: true, message: '请输入SPU名称', trigger: 'blur' }],
                tmId: [{ required: true, message: '请选择品牌' }],
                description: [{ required: true, message: '请输入SPU名称', trigger: 'blur' }],
                // 上传组件不是表单元素 触发方式是什么其实都不生效  需要使用完整验证
                spuImageList: [{ required: true, message: '请上传SPU图片', trigger: 'blur' }],
                spuSaleAttrList: [{ required: true, message: '请添加SPU销售属性', trigger: 'blur' }],
            },
            // 获取环境变量
            baseUrl: '',
        }
    },
    mounted() {
        // 获取环境变量
        this.baseUrl = process.env.VUE_APP_BASE_API
        // 如果是点击添加进入的，我们需要获取 1.品牌列表 2.销售属性列表
        // 如果是点击修改进入的，我们不仅要获取上面两个，还需要获取 1.SPU图片列表 2.销售属性值列表
        // 通过props传递过来的数据判断是点击的添加还是修改，如果有id就是修改  如果没id就是添加
        if (this.spuForm.id) {//有id 修改进入
            this.getEditInitInfo()
        } else {//没有id 添加进入
            this.getAddInitInfo()
        }
        this.$nextTick(() => {
            this.ruleForm = this.$refs.ruleForm
        })
    },
    methods: {
        // 点击添加进入这个页面所要发送的请求
        async getAddInitInfo() {
            const promise1 = spuApi.getTrademarkList()
            const promise2 = spuApi.getBaseSaleAttrList()
            try {
                const res = await Promise.all([promise1, promise2])
                this.trademarkList = res[0].data
                this.baseSaleAttrList = res[1].data
            } catch (error) {
                console.log(error);
                Message.error('点击添加初始化数据失败')
            }
        },
        // 点击修改进入这个页面索要发送的请求
        async getEditInitInfo() {
            const promise1 = spuApi.getTrademarkList()
            const promise2 = spuApi.getBaseSaleAttrList()
            const promise3 = skuApi.getSpuImageList(this.spuForm.id)
            const promise4 = skuApi.etSpuSaleAttrList(this.spuForm.id)
            try {
                const res = await Promise.all([promise1, promise2, promise3, promise4])
                this.trademarkList = res[0].data
                this.baseSaleAttrList = res[1].data
                this.spuForm.spuImageList = res[2].data.map(item => {
                    return {
                        ...item,
                        name :item.imgName,
                        url :item.imgUrl
                    }
                })
                this.spuForm.spuSaleAttrList = res[3].data
            } catch (error) {
                console.log(error);
                Message.error('点击修改初始化数据失败')
            }
        },

        // 图片上传相关函数
        // 上传成功的钩子函数
        handleAvatarSuccess(res, file, fileList) {
            // console.log(res, file, fileList, '88888');
            let arr = []
            fileList.forEach(item => {
                let obj
                if (item.imgName) {
                    obj = item
                } else {
                    obj = {
                        name: item.name,
                        url: item.response.data
                    }
                }
                arr.push(obj)

            })
            this.spuForm.spuImageList = arr
        },
        // 上传文件之前的钩子函数
        beforeAvatarUpload(file) {
            // file为上传的文件
            // console.log(file,'99999');
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                Message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                Message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        // 删除某个图片的回调
        handleRemove(file, fileList) {
            //  console.log(file, fileList,'......');
            let arr = []
            fileList.forEach(item => {
                let obj
                if (item.imgName) {
                    obj = item
                } else {
                    obj = {
                        name: item.name,
                        url: item.response.data
                    }
                }
                arr.push(obj)
            })
            this.spuForm.spuImageList = arr

        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },


        // 删除某个售卖属性值
        delSaleAttrValueName(index) {
            row.splice(index, 1)
        },
        // 变成ipt
        toInput(row) {
            this.$set(row, 'isEdit', true)
            this.$nextTick(() => {
                this.$refs.saveTagInput.focus()
            })
        },
        // 变成btn
        toButton(row) {
            console.log(row.newTag);
            console.log(row);
            if (!row.newTag?.trim()) {//输入为空
                row.isEdit = false
                row.newTag = ''
                Message.warning('输入为空')
                return
            }
            //输入不为空
            const flag = row.spuSaleAttrValueList?.some(item => item.saleAttrValueName === row.newTag)
            if (flag) {//有相同的属性
                row.isEdit = false
                row.newTag = ''
                Message.warning('属性值重复')
                return
            }
            //没有相同的属性，可以添加进去
            let obj = {
                baseSaleAttrId: row.baseSaleAttrId,  //需要 代表属性值所属属性的id，给哪个属性加属性值
                saleAttrValueName: row.newTag//需要 代表属性值的名称
            }
            row.spuSaleAttrValueList.push(obj)
            row.isEdit = false
            row.newTag = ''
        },
        // 删除某个售卖属性
        delSaleAttr(index) {
            this.spuForm.spuSaleAttrList.splice(index, 1)
        },

        // 添加售卖属性
        addSaleAttr() {
            console.log();
            let obj = {
                // spuId: this.spuForm.id,
                baseSaleAttrId:this.spuForm.saleAttr?.split(':')[0],
                saleAttrName: this.spuForm.saleAttr?.split(':')[1],
                spuSaleAttrValueList:[]

            }
            this.spuForm.spuSaleAttrList.push(obj)
            this.spuForm.saleAttr = ''
        },

        // 取消按钮
        cancel() {
            this.$emit('changeStatus', 0)
        },
        // 保存按钮
        async save() {
            try {
                await this.$refs['ruleForm'].validate()
                let spuData = this.spuForm
                spuData.category3Id = this.category3Id
                delete spuData.saleAttr
                spuData.spuSaleAttrList.forEach(item => {
                    delete item.isEdit
                    delete item.newTag
                })
                spuData.spuImageList = spuData.spuImageList.map(item => {
                    return {
                        imgName: item.name,
                        imgUrl: item.imgUrl || item.url
                    }
                })
                console.log(spuData,'/////');
                await spuApi.saveSpuInfo(spuData)
                Message.success('保存成功')
                this.$emit('changeStatus', 0)
            } catch (error) {
                console.log(error);
                Message.error('*内容必须填写')
            }
        }
    },
    computed: {
        ...mapState('category',['category3Id']),
        unSelectedAttr() {
            return this.baseSaleAttrList.filter(item1 => {
                return this.spuForm.spuSaleAttrList?.every(item2 => {
                    return item1.name !== item2.saleAttrName
                })
            })
        }
    }

}
</script>

<style lang="scss">
.el-tag+.el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>
